package com.edu.whty.controller;

import com.alibaba.fastjson.JSON;
import com.edu.whty.common.constants.CodeConstants;
import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.HttpClient;
import com.edu.whty.common.tools.MapUtils;
import com.edu.whty.common.tools.QRCodeGenerator;
import com.edu.whty.common.tools.UUIDUtils;
import com.edu.whty.common.tools.redis.RedisUtil;
import com.edu.whty.entity.base.AttachFile;
import com.edu.whty.entity.base.CloudPage;
import com.edu.whty.entity.base.JobMonitor;
import com.edu.whty.entity.base.ResponseEntity;
import com.edu.whty.entity.cloud.*;
import com.edu.whty.entity.share.ResShare;
import com.edu.whty.service.AttachFileService;
import com.edu.whty.service.CourseService;
import com.edu.whty.service.JobMonitorService;
import com.edu.whty.service.ResShareService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/cloud")
public class CloudController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CourseService courseService;

    @Autowired
    private AttachFileService attachFileService;

    @Autowired
    private JobMonitorService jobMonitorService;

    @Autowired
    private ResShareService resShareService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${rrtbk.streamUrl}")
    private String streamUrl;

    @Value("${rrtbk.isCloud}")
    private boolean isCloud;

    @RequestMapping(value = "/test")
    public ResponseEntity test() {
        return ResponseEntity.getSuccessResponse();

    }

    @RequestMapping(value = "/moveCloud", method = RequestMethod.POST)
    public ResponseEntity moveCloud(HttpServletRequest request, HttpServletResponse response,
                                    @RequestBody MoveCloudReq moveCloud) {
        try {
            if (null == moveCloud) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (StringUtils.isEmpty(moveCloud.getUserId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId不能为空");
                }
                if (StringUtils.isEmpty(moveCloud.getChapterId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "chapterId不能为空");
                }
            }
            courseService.moveCloud(moveCloud);
            return ResponseEntity.getSuccessResponse();
        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("移动资源发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "移动资源发生异常");
        }
    }

    @RequestMapping(value = "/deleteCloud", method = RequestMethod.POST)
    public ResponseEntity deleteCloud(HttpServletRequest request, HttpServletResponse response,
                                      @RequestBody DeleteCloudReq deleteCloudReq) {
        try {
            if (null == deleteCloudReq) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (StringUtils.isEmpty(deleteCloudReq.getUserId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId不能为空");
                }
                if (deleteCloudReq.getList() == null || deleteCloudReq.getList().size() == 0) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "list不能为空");
                }
            }
            String netIp = null == request.getAttribute("netIp") ? null : request.getAttribute("netIp").toString();
            courseService.deleteCloud(deleteCloudReq, netIp);
            request.setAttribute("deleteCloudReq",deleteCloudReq);
            return ResponseEntity.getSuccessResponse();
        } catch (Exception e) {
            logger.error("删除资源发生异常" + e.getMessage());
            // 捕捉异常构造返回信息
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "删除资源发生异常");
        }
    }

    @RequestMapping(value = "/saveCloudRes", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity saveCloudRes(HttpServletRequest request,@RequestBody List<UserResRequest2> userResList, @RequestParam("isPackage") String isPackage,
                                       @RequestParam(required = false ,name = "flag") String flag) {
        try {
            if (userResList != null && userResList.size() > 0) {

                Map<String, Object> map = courseService.saveCloudRes(userResList, isPackage,flag);
                request.setAttribute("map",map);
                return ResponseEntity.getSuccessResponse(map);
            }else {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "添加资源发生异常");
            }

        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("添加资源发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "添加资源发生异常");

        }
    }

    @RequestMapping(value = "/updateResourceInfo", method = RequestMethod.POST)
    public ResponseEntity updateResourceName(HttpServletRequest request, HttpServletResponse response,
                                             @RequestBody UpdateResourceInfo baseRequest) {
        try {
            if (null == baseRequest) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            }
            if (StringUtils.isEmpty(baseRequest.getResId())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "resId不能为空");
            }
            if (StringUtils.isEmpty(baseRequest.getName())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "新name不能为空");
            }
            if (StringUtils.isEmpty(baseRequest.getUserId())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId不能为空");
            }
            courseService.updateResourceInfo(baseRequest);

            TbCourseRes res = courseService.getResByResId(baseRequest.getResId());

            return ResponseEntity.getSuccessResponse(res);
        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("修改资源发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "修改资源发生异常");
        }
    }

    @RequestMapping(value = "/cloudList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity cloudList(HttpServletRequest request, HttpServletResponse response,
                                    @RequestBody CloudPageReq cloudPage) {
        //云端才有熔断
        if(isCloud&&redisUtil.hasKey("key")){
            ResponseEntity re = ResponseEntity.getFailedResponse("910002", "xxxxxxx");
            CloudPage<TbCourseRes> list = new CloudPage<TbCourseRes>();
            list.setList(new ArrayList<TbCourseRes>());
            re.setData(list);
            return re;
        }
        try {
            if (null == cloudPage) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getUserId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId 不能为空");
                }
                if (org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getType())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "type 不能为空");

                }
                if (Constant.SHARE_GUIDANCE.equals(cloudPage.getType())
                        && org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getShareType())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "type 类型为1时必须传sharetype");
                }
                if (Constant.SHARE_GUIDANCE.equals(cloudPage.getType())
                        && Constant.SHARE_COLLECTIVE_PREPARATION.equals(cloudPage.getShareType())
                        && org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getOrgId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "type 类型为1,shareType为8时,必须传orgId");
                }
                if (Constant.SHARE_GUIDANCE.equals(cloudPage.getType())
                        && Constant.SHARE_TYPE_PRIVINCE.equals(cloudPage.getShareType())
                        && org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getPrivinceCode())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "type 类型为1,shareType为10时,必须传privinceCode");
                }
                if (Constant.SHARE_GUIDANCE.equals(cloudPage.getType())
                        && Constant.SHARE_TYPE_CITY.equals(cloudPage.getShareType())
                        && org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getCityCode())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "type 类型为1,shareType为11时,必须传cityCode");

                }
                if (Constant.SHARE_GUIDANCE.equals(cloudPage.getType())
                        && Constant.SHARE_TYPE_AREA_NEW.equals(cloudPage.getShareType())
                        && org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getAreaCode())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "type 类型为1,shareType为12时,必须传areaCode");
                }
            }
            CloudPage<TbCourseRes> pageList = courseService.cloudList(cloudPage);
            List<TbCourseRes> resList = pageList.getList();
            if (resList != null && resList.size() > 0){
                /*for (TbCourseRes tbCourseRes : resList) {

                    if (tbCourseRes.getFid() != null && !isCloud) {
                        AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(tbCourseRes.getFid()));
                        if (attachFile != null && org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                            String downloadUrl = "";
                            if (attachFile.getFilePathRemote().contains("data1")) {
                                downloadUrl = streamUrl + attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                            } else {
                                downloadUrl = streamUrl + "/data1" + attachFile.getFilePathRemote();
                            }
                            tbCourseRes.setDownUrl(downloadUrl);
                            if (Constant.picList.contains(attachFile.getFileExt().toLowerCase()) || Constant.videoList.contains((attachFile.getFileExt().toLowerCase()))) {
                                tbCourseRes.setPreviewUrl(downloadUrl);
                            } else {
                                tbCourseRes.setPreviewUrl("");
                            }
                        } else {
                            tbCourseRes.setPreviewUrl("");
                            tbCourseRes.setDownUrl("");
                        }
                    }
                }*/
                logger.info("/cloudList请求成功 req:"+cloudPage.toString()+" 列表大小 size:"+pageList.getList().size());
        }
            return ResponseEntity.getSuccessResponse(pageList);
        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("资源列表发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, e.getMessage());

        }
    }

    @RequestMapping(value = "/queryCloudRes", method = RequestMethod.POST)
    public ResponseEntity queryCloudRes(HttpServletRequest request, HttpServletResponse response,
                                        @RequestBody UserResRequest2 userResRequest) {
        try {
            if (null == userResRequest) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(userResRequest.getResId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "resId不能为空");
                }

                TbCourseRes res = courseService.getResByResId(userResRequest.getResId());

               /* if(res.getFid()!=null&&!isCloud&&!Constant.IS_PACKAGE.equals(res.getIsPackage())){
                    AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(res.getFid()));
                    if(attachFile != null&& org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                        String downloadUrl = "";
                        if(attachFile.getFilePathRemote().contains("data1")) {
                            downloadUrl = streamUrl + attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                        }else {
                            downloadUrl = streamUrl +"/data1"+attachFile.getFilePathRemote();
                        }
                        res.setDownUrl(downloadUrl);
                        if (Constant.picList.contains(attachFile.getFileExt().toLowerCase()) || Constant.videoList.contains((attachFile.getFileExt().toLowerCase()))) {
                            res.setPreviewUrl(downloadUrl);
                        }else {
                            res.setPreviewUrl("");
                        }
                    }else {
                        res.setDownUrl("");
                        res.setPreviewUrl("");
                    }
                }else*/ if(res.getFid()!=null&&isCloud&&!Constant.IS_PACKAGE.equals(res.getIsPackage())&&!res.getPreviewUrl().contains("wpslinuxv2.huijiaoyun.com")){
                    String cloudPreviewUrl= ""; // 云端预览地址
                    String cloudDownloadUrl= "";
                    String url = "http://filecenter.huijiaoyun.com/filecenter/upload/getAttachFileByFid/" + res.getFid();
                    String result = HttpClient.doGetMethod(url);
                    JSONObject j = JSONObject.fromObject(result);
                    if ("000000".equals(j.getString("code"))) {
                        JSONObject data1 = j.getJSONObject("data");

                        if (StringUtils.isNotBlank(data1.getString("previewUrl"))) {
                            cloudPreviewUrl = data1.getString("previewUrl");
                            logger.info(res.getFid()+"..."+cloudPreviewUrl);
                            res.setPreviewUrl(cloudPreviewUrl);
                        }
                        if (StringUtils.isNotBlank(data1.getString("downloadUrl"))) {
                            cloudDownloadUrl = data1.getString("downloadUrl");
                            res.setDownUrl(cloudDownloadUrl);
                        }
                    }
                }
                if(Constant.IS_PACKAGE.equals(res.getIsPackage())) {
                    List<TbCourseRes> resList = courseService.getResByPackageId(res.getResId());
                    Long fileLength = 0L;
                    for(TbCourseRes tbCourseRes:resList){
                        fileLength = fileLength + Long.valueOf(tbCourseRes.getFileLength());
                    }
                    res.setFileLength(fileLength.toString());
                    res.setFileSize(parseFileStorage(fileLength));
                    res.setResList(resList);
                }
                return ResponseEntity.getSuccessResponse(res);
            }
        } catch (Exception e) {
            logger.error("查询资源详情异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "查询资源详情异常");
        }
    }


    @RequestMapping(value = "/queryCloudResBaoAn", method = RequestMethod.POST)
    public ResponseEntity queryCloudResBaoAn(HttpServletRequest request, HttpServletResponse response,
                                        @RequestBody UserResRequest2 userResRequest) {
        try {
            if (null == userResRequest) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(userResRequest.getResId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "resId不能为空");
                }

                TbCourseRes res = courseService.getResByResId(userResRequest.getResId());

                if(res.getFid()!=null&&!isCloud&&!Constant.IS_PACKAGE.equals(res.getIsPackage())){
                    AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(res.getFid()));
                    if(attachFile != null&& org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                        String downloadUrl = "";
                        if(attachFile.getFilePathRemote().contains("data1")) {
                            downloadUrl = streamUrl + attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                        }else {
                            downloadUrl = streamUrl +"/data1"+attachFile.getFilePathRemote();
                        }
                        res.setDownUrl(downloadUrl);
                        if (Constant.picList.contains(attachFile.getFileExt().toLowerCase()) || Constant.videoList.contains((attachFile.getFileExt().toLowerCase()))) {
                            res.setPreviewUrl(downloadUrl);
                        }else {
                            res.setPreviewUrl("");
                        }
                    }else {
                        res.setDownUrl("");
                        res.setPreviewUrl("");
                    }
                }else if(res.getFid()!=null&&isCloud&&!Constant.IS_PACKAGE.equals(res.getIsPackage())&&!res.getPreviewUrl().contains("wpslinuxv2.huijiaoyun.com")){
                    String cloudPreviewUrl= ""; // 云端预览地址
                    String cloudDownloadUrl= "";
                    String url = "http://filecenter.huijiaoyun.com/filecenter/upload/getAttachFileByFid/" + res.getFid();
                    String result = HttpClient.doGetMethod(url);
                    JSONObject j = JSONObject.fromObject(result);
                    if ("000000".equals(j.getString("code"))) {
                        JSONObject data1 = j.getJSONObject("data");

                        if (StringUtils.isNotBlank(data1.getString("previewUrl"))) {
                            cloudPreviewUrl = data1.getString("previewUrl");
                            logger.info(res.getFid()+"..."+cloudPreviewUrl);
                            res.setPreviewUrl(cloudPreviewUrl);
                        }
                        if (StringUtils.isNotBlank(data1.getString("downloadUrl"))) {
                            cloudDownloadUrl = data1.getString("downloadUrl");
                            res.setDownUrl(cloudDownloadUrl);
                        }
                    }
                }
                if(Constant.IS_PACKAGE.equals(res.getIsPackage())) {
                    List<TbCourseRes> resList = courseService.getResByPackageId(res.getResId());
                    Long fileLength = 0L;
                    for(TbCourseRes tbCourseRes:resList){
                        fileLength = fileLength + Long.valueOf(tbCourseRes.getFileLength());
                    }
                    res.setFileLength(fileLength.toString());
                    res.setFileSize(parseFileStorage(fileLength));
                    res.setResList(resList);
                }
                return ResponseEntity.getSuccessResponse(res);
            }
        } catch (Exception e) {
            logger.error("查询资源详情异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "查询资源详情异常");
        }
    }



    @RequestMapping(value = "/initCourseResList", method = RequestMethod.POST)
    public ResponseEntity initCourseResList(HttpServletRequest request, HttpServletResponse response,
                                    @RequestBody CloudPageReq cloudPage) {
        try {
            if (null == cloudPage) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getOrgId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "orgId不能为空");
                }
                List<TbCourseRes> courseResList = courseService.initCourseResList(cloudPage);
                return ResponseEntity.getSuccessResponse(courseResList);
            }
        } catch (Exception e) {
            logger.error("获取CourseRes初始化列表异常：" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "获取CourseRes初始化列表异常");
        }
    }

    @RequestMapping(value = "/initCourseUserList", method = RequestMethod.POST)
    public ResponseEntity initCourseUserList(HttpServletRequest request, HttpServletResponse response,
                                    @RequestBody CloudPageReq cloudPage) {
        try {
            if (null == cloudPage) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getOrgId()) &&
                        org.apache.commons.lang.StringUtils.isEmpty(cloudPage.getUserId()) &&
                        cloudPage.getUserIdList().size() == 0) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "orgId或userId不能为空");
                }
                List<TbCourseUser> courseUserList = courseService.initCourseUserList(cloudPage);
                return ResponseEntity.getSuccessResponse(courseUserList);
            }
        } catch (Exception e) {
            logger.error("获取CourseUser初始化列表异常：" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "获取CourseUser初始化列表异常");
        }
    }

    @RequestMapping(value = "/statCloud", method = RequestMethod.POST)
    public ResponseEntity statCloud(@RequestBody JSONObject obj){
        Map<String, Object> data = MapUtils.newHashMap();
        String type = obj.optString("type");
        String idArr = obj.optString("idArr");
        String userId = obj.optString("userId");
        TbCourseRes tbCourseRes = new TbCourseRes();
        tbCourseRes.setCreatorId(userId);
        String[] ids=idArr.split(",");
        try {
            for(String id: ids) {
                if ("1".equals(type)) {
                    tbCourseRes.setPlatformResId(id);
                }else if ("2".equals(type)){
                    tbCourseRes.setPlatformProductCode(id);
                }else {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "必须传type");
                }
                if(courseService.statCloud(tbCourseRes)!=0){
                    data.put(id,1);
                }else {
                    data.put(id,0);
                }
             }
             return ResponseEntity.getSuccessResponse(data);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "查询失败");
        }
    }

    @RequestMapping(value = "/addDownCount", method = RequestMethod.POST)
    public ResponseEntity queryCloudRes(HttpServletRequest request, HttpServletResponse response,
                                        @RequestBody TbCourseRes param) {
        try {
            if (null == param) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(param.getResId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "resId不能为空");
                }
                TbCourseRes tbCourseRes = courseService.getResByResId(param.getResId());
                tbCourseRes.setDownCount(tbCourseRes.getDownCount()+param.getDownCount());
                courseService.updateCloud(tbCourseRes);
                return ResponseEntity.getSuccessResponse(tbCourseRes.getDownCount());
            }
        } catch (Exception e) {
            logger.error("增加资源下载次数异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "增加资源下载次数");
        }
    }


    /**
     * 修改资源协同状态和类型
     * @param request
     * @param response
     * @param param
     * @return
     */
    @RequestMapping(value = "/updateRes", method = RequestMethod.POST)
    public ResponseEntity updateRes(HttpServletRequest request, HttpServletResponse response,
                                        @RequestBody TbCourseRes param) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String teamTime = sdf.format(new Date());
        try {
            if (null == param) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(param.getResId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "resId不能为空");
                }
                logger.info("修改资源id:"+param.getResId()+"修改信息:"+ JSON.toJSONString(param));
                TbCourseUser tbCourseUser = courseService.getUserByResId(param.getResId());
                TbCourseRes tbCourseRes = courseService.getResByResId(param.getResId());
                tbCourseUser.setTeamStatus(param.getTeamStatus());
                tbCourseUser.setTeamType(param.getTeamType());
                if("0".equals(param.getTeamType())){
                    tbCourseUser.setTeamTime(teamTime);
                }
                tbCourseUser.setIsEdit(param.getIsEdit());
                tbCourseUser.setUploadCos(param.getUploadCos());
                tbCourseUser.setFid(param.getFid());
                tbCourseUser.setTitle(param.getTitle());
                tbCourseUser.setIsShare(param.getIsShare());
                tbCourseRes.setPreviewUrl(param.getPreviewUrl());
                tbCourseRes.setDownUrl(param.getDownUrl());
                tbCourseRes.setFid(param.getFid());
                tbCourseRes.setSrcFid(param.getFid());
                tbCourseRes.setTitle(param.getTitle());
                courseService.updateCloud(tbCourseRes);
                courseService.updateBycourseResId(tbCourseUser);
                return ResponseEntity.getSuccessResponse(tbCourseRes.getResId());
            }
        } catch (Exception e) {
            logger.error("增加资源下载次数异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "增加资源下载次数");
        }
    }

    private String parseFileStorage(Long fileLength) {
        String fileStorage = "";
        DecimalFormat df = new DecimalFormat("#.00");
        if(fileLength<1024L) {
            fileStorage = df.format((double) fileLength) + "B";
        }else if (fileLength < 1024*1024L) {
            fileStorage = df.format((double) fileLength/1024) + "KB";
        }else if (fileLength < 1024*1024*1024L) {
            fileStorage = df.format((double) fileLength/(1024*1024)) + "MB";
        }else if(fileLength < 1024*1024*1024*1024L){
            fileStorage = df.format((double) fileLength/(1024*1024*1024)) + "GB";
        }else {
            fileStorage = df.format((double) fileLength/(1024*1024*1024*1024)) + "TB";
        }
        return fileStorage;
    }

    @RequestMapping(value = "/updateStat/{resId}", method = RequestMethod.GET)
    public ResponseEntity finishUpSyncCourseUser(@PathVariable String resId) {
        try {
            courseService.finishUpSyncCourseUserByOrgId(resId);
            courseService.finishUpSyncCourseResByOrgId(resId);
            logger.info("修改同步状态完成");
            return ResponseEntity.getSuccessResponse("同步成功");
        } catch (Exception e) {
            logger.error("修改同步状态" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "修改同步状态");
        }
    }

    @RequestMapping(value = "/qrImage/{shareId}", method = RequestMethod.GET)
    public org.springframework.http.ResponseEntity<byte[]> getQRImage(@PathVariable String shareId) {


        byte[] qrCode = null;
        try {
            ResShare resShare = new ResShare();
            resShare.setShareId(shareId);
            ResShare resShare0= resShareService.getResShare(resShare);
            if(resShare0 !=null) {
                qrCode = QRCodeGenerator.getQRCodeImage(resShare0.getPreviewUrl(), 177, 177);
            }
        } catch (Exception e) {
            logger.error("Could not generate QR Code, WriterException :: " + e.getMessage());
            return null;
        }

        // Set headers
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        return new org.springframework.http.ResponseEntity<>(qrCode, headers, HttpStatus.CREATED);

    }

    @RequestMapping(value = "/addSynJxzsJob", method = RequestMethod.POST)
    public ResponseEntity  addSynJxzsJob(@RequestBody CloudPageReq param){
        ResponseEntity responseEntity = ResponseEntity.getSuccessResponse();
        if(StringUtils.isEmpty(param.getUserId())||StringUtils.isEmpty(param.getPlatformCode())){
            responseEntity = ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR,"缺少必传参数");
            return responseEntity;
        }
        JobMonitor jobMonitor = jobMonitorService.getJxzsJobMonitor(param.getUserId());
        if(jobMonitor != null){
            if("0".equals(jobMonitor.getStatus())){
                responseEntity = ResponseEntity.getFailedResponse("111111","正在执行同步任务");
                return responseEntity;
            }else if("1".equals(jobMonitor.getStatus())){
                responseEntity = ResponseEntity.getFailedResponse("222222","同步任务已完成");
                return responseEntity;
            }

        }
        JobMonitor jobMonitorAdd = new JobMonitor();
        jobMonitorAdd.setJobId(UUIDUtils.getRandomUUID());
        jobMonitorAdd.setSynTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        jobMonitorAdd.setStatus("0");
        jobMonitorAdd.setUserIds(param.getUserId());
        jobMonitorAdd.setPlatformCode(param.getPlatformCode());
        jobMonitorService.addJxzsJobMonitor(jobMonitorAdd);
        responseEntity.setResMsg("新建同步任务成功");
        return responseEntity;
    }

    @RequestMapping(value = "/operateRedis/{type}", method = RequestMethod.GET)
    public ResponseEntity  operateRedis(@PathVariable Integer type) {
        if(type==0){
            redisUtil.del("key");
        }else if(type==1){
            redisUtil.set("key","1");
        }
        ResponseEntity responseEntity = ResponseEntity.getSuccessResponse();
        responseEntity.setResMsg("操作成功");
        return responseEntity;
    }


    @RequestMapping(value = "/saveUsrRes", method = RequestMethod.POST)
    public ResponseEntity  saveUsrRes(@RequestBody com.alibaba.fastjson.JSONObject json) {
        ResponseEntity responseEntity = ResponseEntity.getSuccessResponse();
        String optType = json.getString("optType");
        try{
            if("1".equals(optType)){
                courseService.saveUserRes(json);
                responseEntity.setResMsg("新增成功");
            }else if("2".equals(optType)){
                courseService.delUserRes(json);
                responseEntity.setResMsg("删除成功");
            }else if("3".equals(optType)){
                courseService.updateUserRes(json);
                responseEntity.setResMsg("修改成功");
            }else if("4".equals(optType)){
                courseService.moveUserRes(json);
                responseEntity.setResMsg("移动成功");
            }

        }catch (Exception e){
            e.printStackTrace();
            responseEntity.setResCode("111111");
            responseEntity.setResMsg(e.getMessage());
            responseEntity.setData(e);
        }
        return responseEntity;
    }

    @RequestMapping(value = "/updateUsrRes", method = RequestMethod.POST)
    public ResponseEntity  updateUsrRes(@RequestBody com.alibaba.fastjson.JSONObject json) {
        ResponseEntity responseEntity = ResponseEntity.getSuccessResponse();
        try{
            courseService.updateStatus(json);
            responseEntity.setResMsg("同步成功");
        }catch (Exception e){
            e.printStackTrace();
            responseEntity.setResCode("111111");
            responseEntity.setResMsg("新增失败");
        }


        return responseEntity;
    }



    @RequestMapping(value = "/handSyncRrtToJxzs/{courseId}", method = RequestMethod.GET)
    public ResponseEntity  handSyncRrtToJxzs(@PathVariable String courseId) {
        ResponseEntity responseEntity = ResponseEntity.getSuccessResponse();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            TbCourseUser tbCourseUser = courseService.getUserByCourseId(courseId);
            TbCourseRes tbCourseRes = courseService.getResByResId(tbCourseUser.getCourseResid());
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
            data.put("optType","1");
            data.put("source","rrtpc");
            data.put("sourceId",courseId);
            data.put("title",tbCourseUser.getTitle());
            data.put("fileSize",tbCourseRes.getFileSize());
            data.put("fileLength",tbCourseRes.getFileLength());
            data.put("fId",tbCourseRes.getFid());
            data.put("md5",tbCourseRes.getMd5());
            data.put("fileExt",tbCourseRes.getFileExt());
            data.put("classfiitonTypeId",tbCourseRes.getClassfiitonId());
            data.put("userId",tbCourseRes.getCreatorId());
            data.put("userName",tbCourseRes.getCreatorName());
            data.put("platformCode",tbCourseRes.getLoginPlatformCode());
            data.put("loginPlatformCode",tbCourseRes.getLoginPlatformCode());
            data.put("previewUrl",tbCourseRes.getPreviewUrl());
            data.put("downloadUrl",tbCourseRes.getDownUrl());
            data.put("orgId",tbCourseRes.getOrgId());
            data.put("orgName",tbCourseRes.getOrgName());
            data.put("periodId",tbCourseUser.getCoursePeriodId());
            data.put("periodName",tbCourseUser.getCoursePeriodName());
            data.put("subjectId",tbCourseUser.getCourseSubjectId());
            data.put("subjectName",tbCourseUser.getCourseSubjectName());
            data.put("editionId",tbCourseUser.getCourseEditionId());
            data.put("editionName",tbCourseUser.getCourseEditionName());
            data.put("volumeId",tbCourseUser.getCourseVolumeId());
            data.put("volumeName",tbCourseUser.getCourseVolumeName());
            data.put("textbookId",tbCourseUser.getCourseTextbookId());
            data.put("textbookName",tbCourseUser.getCourseTextbookName());
            data.put("chapterId",tbCourseUser.getCourseChapterid());
            data.put("chapterName",tbCourseUser.getCourseChaptername());
            data.put("createTime",sdf.format(new Date()));
            data.put("updateTime",sdf.format(new Date()));
            json.put("classRoomId",data.toJSONString());
            json.put("type","12");
            json.put("createTime",System.currentTimeMillis());
            json.put("userId",tbCourseRes.getCreatorId());
            json.put("loginPlatformCode",tbCourseRes.getLoginPlatformCode());
            json.put("platformCode","http://rrtbk.rrt-pc.svc.cluster.local:8080/rrtbk-api/cloud/updateUsrRes");
            com.alibaba.fastjson.JSONObject finalJson = new com.alibaba.fastjson.JSONObject();
            finalJson.put("userSessionId", "jxzsRes");
            finalJson.put("platformCode", StringUtils.isEmpty(tbCourseUser.getPlatformCode()) ? tbCourseUser.getPlatformCode() : tbCourseUser.getLoginPlatformCode());
            finalJson.put("loginPlatformCode", tbCourseUser.getLoginPlatformCode());
            finalJson.put("topic", "jxzsRes");
            finalJson.put("data", json.toJSONString());

            String upSyncUrl = "http://kcapi.huijiaoyun.com/res-course/logMessage/saveKafka";
            String jsonStr = com.alibaba.fastjson.JSONObject.toJSONString(finalJson);
            String textbookResponse = HttpClient.doJSONPostMethod(upSyncUrl, jsonStr);
            System.out.println(textbookResponse);
            responseEntity.setResMsg("同步成功");
        }catch (Exception e){
            e.printStackTrace();
            responseEntity.setResCode("111111");
            responseEntity.setResMsg("新增失败");
        }


        return responseEntity;
    }



    /**
     * 查询朗鹰数据
     * @param
     * @param
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/queryLyData", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity queryLyData(@RequestBody CloudPageReq cloudPage) {
        try {
            Map map = new HashMap();
            //String startTime = json.getString("startTime");
            //String endTime = json.getString("endTime");
            map.put("startTime",cloudPage.getStartTime());
            map.put("endTime",cloudPage.getEndTime());
            List<TbCourseRes> list = courseService.queryLyData(map);
            return ResponseEntity.getSuccessResponse(list);
        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("添加资源发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "查询资源发生异常");

        }
    }





    /**
     * 习题加入备课接口
     * @param request
     * @param userResList
     * @param isPackage
     * @param
     * @return
     */
    @RequestMapping(value = "/saveXitiCloudRes", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity saveXitiCloudRes(HttpServletRequest request,@RequestBody List<UserResRequest2> userResList, @RequestParam("isPackage") String isPackage) {
        try {
            if (userResList != null && userResList.size() > 0) {

                Map<String, Object> map = courseService.saveXitiCloudRes(userResList, isPackage);
                //request.setAttribute("map",map);
                return ResponseEntity.getSuccessResponse(map);
            }else {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "添加资源发生异常");
            }

        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("添加资源发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "添加资源发生异常");

        }
    }


}
